package com.ruoyi.system.utils;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
public class DeptUtils {
  
  private static SysDeptMapper sysDeptMapper;
  private static SysUserMapper sysUserMapper;
  @Autowired
  private SysDeptMapper mapper;
  @Autowired
  private SysUserMapper UserMapper;

  
  @PostConstruct
  public void init() {
    sysDeptMapper = this.mapper;
  }

  @PostConstruct
  public void initUser() {
    sysUserMapper = this.UserMapper;
  }
  
  public static String getInstitutionIdsBySysUser(SysUser user) {
    SysDept sysDept = user.getDept();
    if (null == sysDept) {
      throw new RuntimeException("用户所属部门不存在");
    }
    List<SysDept> lstSysDepts = new ArrayList<>();
    lstSysDepts.add(sysDept);
    lstSysDepts.addAll(sysDeptMapper.selectChildrenDeptById(sysDept.getDeptId()));
    StringBuffer institutionIds = new StringBuffer("-1");
    for (int i = 0; i < lstSysDepts.size(); i++) {
      Long lSubSysDeptId = getLongByObject(lstSysDepts.get(i).getDeptId());
      if (-1 != lSubSysDeptId) {
        institutionIds.append("," + lSubSysDeptId);
      }
    }
    return institutionIds.toString();
  }
  
  public static Long getLongByObject(Object o) {
    Long id = -1L;
    try {
      id = (Long) Long.valueOf(String.valueOf(o).trim());
    } catch (Exception e) {
    }
    return id;
  }
}
